package com.csap.framework.oauth2.security.dynamic;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.listener.Listener;
import com.csap.framework.oauth2.security.Oauth2SecurityProperties;
import com.csap.framework.oauth2.security.RouterCache;
import com.csap.framework.oauth2.security.SecurityBeanFilter;
import com.csap.framework.oauth2.security.SecurityFilter;
import com.csap.framework.util.bean.BeanCopierUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.util.concurrent.Executor;

/**
 * 权限动态刷新-nacos
 *
 * @Author ycf
 * @Date 2021/9/23 9:41 下午
 * @Version 1.0
 */
@Slf4j
public class SecurityDynamicNacos {
    private final NacosConfigManager nacosConfigManager;
    private final Oauth2SecurityProperties oauth2SecurityProperties;
    private final SecurityFilter securityFilter;

    public SecurityDynamicNacos(NacosConfigManager nacosConfigManager, Oauth2SecurityProperties oauth2SecurityProperties, SecurityFilter securityFilter) {
        this.nacosConfigManager = nacosConfigManager;
        this.oauth2SecurityProperties = oauth2SecurityProperties;
        this.securityFilter = securityFilter;
        addListener();
    }

    @SneakyThrows
    private void addListener() {
        nacosConfigManager.getConfigService().addListener(oauth2SecurityProperties.getDataId(), oauth2SecurityProperties.getGroup(), new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                if (log.isDebugEnabled()) {
                    log.debug("SecurityDynamicNacos :{}, receiveConfigInfo:{}", Oauth2SecurityProperties.PREFIX, configInfo);
                }
                Oauth2SecurityNacos oauth2SecurityNacos = new Yaml().loadAs(configInfo, JSONObject.class).toJavaObject(Oauth2SecurityNacos.class);
                BeanCopierUtil.copy(oauth2SecurityNacos.getCsap().getOauth2().getSecurity(), oauth2SecurityProperties);
                SecurityBeanFilter.securityFilter(securityFilter, oauth2SecurityNacos.getCsap().getOauth2().getSecurity(), true);
                RouterCache.clear();
            }
        });
    }
}
